package com.aaa.zs.filter;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.aaa.zs.service.RemoteLoginService;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    //优先级要比跨域、安全过滤的低
    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Autowired
    private RemoteLoginService remoteLoginService;

    @Override
    public Object run() throws ZuulException {
        /**
         * 具体的过滤器的业务方法
         */
        System.out.println("进入到登录过滤器。。。。");
        //获取zuul中提供的上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
//        获取request
        HttpServletRequest request=requestContext.getRequest();
        //获取response对象
        HttpServletResponse response = requestContext.getResponse();

        //获取请求的URI
        String requestURI = request.getRequestURI();
        //获取请求的携带的token
         String accessToken = request.getHeader("accessToken"); //统一把所有的请求头添加token 建议使用
//        String accessToken = request.getParameter("accessToken");//需要请求时，所有请求都加
//        System.out.println(accessToken);
        if(requestURI.contains("/userlogin/auth")
                ||requestURI.contains("/memberlogin/auth")
                ||(!StringUtils.isEmpty(accessToken)&&remoteLoginService.checkToken(accessToken))){
            //放行
            requestContext.setSendZuulResponse(true);
            requestContext.setResponseStatusCode(HttpStatus.SC_OK);
            return null;
        }
        //不放行
        requestContext.setSendZuulResponse(false);
        try {
            Result result=new Result(ResultStatus.FAIL.getCode()
                    ,ResultStatus.FAIL.getMessage(),"nologin");
            String resultJson = JSON.toJSONString(result);
            //返回result的json串
            response.setCharacterEncoding("GBK");
            response.getWriter().print("nologin");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
